// 网络请求失败一次后重试调用网络请求

const rate = 0.5;

const request = () => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      const res = Math.random();
      if (res > rate) {
        resolve(res);
      }
      reject("network error");
    }, 2000);
  });
};

const retry = (fn = () => {}, retryCount = 3, retryTimeOut = 2000) => {
  let count = retryCount;
  const _fn = () => {
    fn()
      .then((res) => {
        console.log("network success", res);
      })
      .catch((e) => {
        console.log(e);
        count--;
        count > 0 &&
          setTimeout(() => {
            console.log("retry now");
            _fn();
          }, retryTimeOut);
      });
  };
  _fn();
};

retry(request);
